<script setup>
import _ from 'lodash';
import {useCommonStore} from "@jzl/stores";
import {api} from "@jzl/api";
import {computed, onMounted, reactive, toRefs} from "vue";

defineOptions({
  name: 'ParameterForm'
})

const emit = defineEmits(['close']);
const props = defineProps({
  //传入一个value，使组件支持v-model绑定
  id: {
    type: [Number, String]
  },
  formInfo: {
    type: Object,
    default: null
  },
  isView: {
    type: Boolean,
    default: false
  },
  show: {
    type: Boolean,
    default: true
  }
})

const {
  projectId,
  inited,
  form,
  custFormItems,
  activeHeader
} = toRefs(reactive({
  projectId: null,
  inited: false,
  form: {
    form_name: '',
    form_code: '',
    project_id: '',
    use_type: 'WEB',
    type: 1,
    cols: 1,
    owner_type: 2,
    owner_row_max: -1,
    is_pay_form: 0,
    service_module: '',
    data_title_tpl: '',
    is_tree: 0,
    theme: "",    // normal | simple | vertical | qing
    style: {
      theme: "simple",      // normal | simple | vertical | qing
      fontSize: "",   // small | medium | large | xl
      icon: "",
      bgColor: "",
      orders: []
    },
    group_nav: {
      theme: "none",  // none | list | tab
      position: "left",   // left | right | top | bottom
      name: "分组导航",
      icon: "fa fa-paper-plane"
    },
    items: [],
    groups: []
  },
  custFormItems: [],
  activeHeader: true
}))

const isUpdate = computed(() => {
  return props.id > 0;
})

onMounted(() => {
  init()
})

const init = async () => {
  const store = useCommonStore();
  let iPid = store?.project?.project_id || store?.loginUser?.project_id; //  _.get(project, 'project_id', null) || _.get(loginUser, "project_id");

  form.value.form_code = $utils.getNanoid(10);
  form.value = _.merge(form.value, props.formInfo, {
    project_id: iPid,
    use_type: 'WEB'
  });
  projectId.value = iPid;
  inited.value = true;
}

const emptyFn = () => {
}

const save = async () => {
  let iForm = _.cloneDeep(form.value);
  let items = _.cloneDeep(custFormItems.value);
  // let form_dimensions = [];
  let actions = _.get(iForm, "actions", []) || [];   // 修改的话，原数据带回去，不然会丢失

  let {kv, invalidFields} = $formUtils.getFormDefineData(iForm, items, actions, false);

  let formDef = _.get(kv, "formInfo");
  let realItems = _.get(kv, "items");
  let groups = _.get(kv, "groups");

  formDef.items = realItems;
  formDef.groups = groups;

  if (invalidFields && invalidFields.length) {
    let msg = invalidFields.join('<br/>');
    $jui.notify({
      title: '提示',
      message: msg,
      dangerouslyUseHTMLString: true,
      type: 'warning'
    });
    return;
  }

  let ret = null;
  if (props.id && props.id > 0) {
    ret = await api.project.updateParamDef(props.id, {
      form_def: formDef
    });
  } else {
    ret = await api.project.createParamDef({
      form_def: formDef
    });
  }

  if (ret) {
    $jui.toast('操作成功！');
    back(true);
  }
}

const back = (flag = false) => {
  if(flag) {
    emit('confirm:win', flag);
  } else {
    emit('cancel:win', flag);
  }
}

const itemSelectedChange = (currentIndex, isEditMode) => {
  if (isEditMode /*&& currentIndex >= 0*/) { // 正在编辑
    activeHeader.value = false;
  }
}

const eidtItemHeader = () => {
  activeHeader.value = true;
}
</script>

<template>
  <div class="survey-create-container">
    <FormItemsDefine
      v-if="inited"
      v-model="custFormItems"
      :form="form"
      :use-type="form.use_type"
      :project-id="projectId"
      :is-show-form="false"
      oper-type="form"
      @selected-item-change="itemSelectedChange"
    ><!--:noborder="true"-->
      <template #item-header>
        <div
          class="survey-item-header"
          :class="{ 'active': activeHeader }"
          @click="eidtItemHeader"
        >
          <h4 v-if="form">
            <div v-text="form.form_name || '参数名称'" :class="{ 'tip': !form.form_name }"></div>
            <p v-text="form.form_code || '参数编码'" :class="{ 'tip': !form.form_code }"></p>
          </h4>
        </div>
      </template>
      <template #prop>
        <el-form
          v-if="activeHeader"
          class="survey-item-props"
          label-width="60px"
        >
          <template v-if="form">
            <el-form-item
              label="表单名称"
              v-tippy
              content="命名规则：仅支持字母/数字/_字符，并不能以数字开头"
            >
              <el-input
                v-model="form.form_name"
                :disabled="isView"
              />
            </el-form-item>
            <el-form-item label="表单编码">
              <el-input
                v-model="form.form_code"
                :disabled="isView || isUpdate"
              />
            </el-form-item>
            <el-form-item label="表单列数">
              <el-radio-group
                v-model="form.cols"
                :disabled="isView"
              >
                <el-radio :label="1">1列</el-radio>
                <el-radio :label="2">2列</el-radio>
                <el-radio :label="3">3列</el-radio>
                <el-radio :label="4">4列</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
          <hr class="m-2" />

          <template v-if="form?.style">
            <el-form-item label="主题样式">
              <el-radio-group v-model="form.style.theme" :disabled="isView">
                <el-radio label="simple">默认</el-radio>
                <!--<el-radio label="simple">简单</el-radio>-->
                <el-radio label="line">线框</el-radio>
                <el-radio label="qing">轻灵</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="文字大小">
              <el-radio-group v-model="form.style.fontSize" :disabled="isView">
                <el-radio label="sm">小号</el-radio>
                <!--<el-radio label="simple">简单</el-radio>-->
                <el-radio label="md">中号</el-radio>
                <el-radio label="lg">大号</el-radio>
                <el-radio label="xl">超大号</el-radio>
              </el-radio-group>
            </el-form-item>

            <!--<el-form-item label="背景色">
                <color-picker v-model="form.style.bgColor"></color-picker>
            </el-form-item>-->

            <el-form-item label="表单图标">
              <div style="display: flex;">
                <icon-picker v-model="form.style.icon" :disabled="isView" style="margin-right: 10px;"></icon-picker>
                <el-color-picker v-model="form.style.color" size="mini" :disabled="isView"></el-color-picker>
              </div>
            </el-form-item>
          </template>
        </el-form>
      </template>
    </FormItemsDefine>
    <div class="survey-create-actions">
      <el-button type="primary" @click="save()"> 保存</el-button>
      <el-button @click="back()"> 取消</el-button>
    </div>
  </div>
</template>
